<template>
  <div ref="parentDiv">
    <Window
      :show="windowConfig.show"
      :width="width"
      :height="height"
      :buttons="windowConfig.buttons"
      @close="closeWindow"
    >
      <el-form
        ref="blogFormRef"
        :model="blogFormData"
        :rules="rules"
        style="display: flex; flex-direction: column; flex: auto"
      >
        <el-form-item prop="title">
          <div class="title-input">
            <el-input
              placeholder="起一个好听的名字"
              v-model="blogFormData.title"
              ><template #prefix
                ><span class="iconfont icon-title"></span></template
            ></el-input>
          </div>
        </el-form-item>
        <el-form-item prop="content" class="textArea">
          <!-- <div :style="{'width':'100%','background':'green','flex':'auto'}">
            
          </div> -->
          <div style="width: 100%; height: 100%">
            <EditorHtml
              v-if="blogFormData.editorType == 0"
              v-model="blogFormData.content"
            ></EditorHtml>
            <EditorMarkdown
              v-else
              @htmlContent="setHtmlContent"
              v-model="blogFormData.markdownContent"
            ></EditorMarkdown>
          </div>
        </el-form-item>
      </el-form>
      


    </Window>
  </div>
</template>

<script setup>
import {
  ref,
  computed,
  reactive,
  getCurrentInstance,
  onMounted,
  nextTick,
  onUnmounted,
} from "vue";
const { proxy } = getCurrentInstance();

const api = {
  saveBlog: "/blog/saveBlog4Special",
  getUserInfo: "/getUserInfo",
  getBlogDetail: "/blog/getBlogById",
  autoSaveBlog: "/blog/autoSaveBlog4Special",
};

const props = defineProps({
  width: {
    type: Number,
    required: true,
  },
  height: {
    type: Number,
    required: true,
  },
  buttons: {
    type: Array,
  },
  showCancel: {
    type: Boolean,
    default: true,
  },
  show: {
    type: Boolean,
    default: false,
  },
});

const rules = {
  title: [{ required: true, message: "请填写标题" }],
  content: [{ required: true, message: "请填写文章内容" }],
  categoryId: [{ required: true, message: "请选择博客分类" }],
  type: [{ required: true, message: "请选择博客类型" }],
  allowComment: [{ required: true, message: "请选择是否允许评论" }],
  reprintUrl: [{ required: true, message: "请输入原文地址" }],
};

// 自动保存
let timer = ref(null);

const startTimer = () => {
  timer.value = setInterval(() => {
    autoSave();
  }, 10000);
};

const cleanTimer = () => {
  if (timer.value != null) {
    clearInterval(timer.value);
    timer.value = null;
  }
};

const autoSave = async () => {
  if (
    (blogFormData.value.title == undefined &&
      blogFormData.value.content == undefined) ||
    timer.value == null
  ) {
    return;
  }
  const params = {};
  Object.assign(params, blogFormData.value);
  let result = await proxy.Request({
    url: api.autoSaveBlog,
    params: params,
  });
  if (!result) {
    return;
  }
  blogFormData.value.blogId = result.data;
};

// 博客内容 新增,修改

// Markdown编辑器回调html
const setHtmlContent = (htmlContent) => {
  blogFormData.value.content = htmlContent;
};

// 博客正文
const blogFormRef = ref({});
const blogFormData = ref({ tag: [] });

// 第一步提交
const windowConfig = ref({
  show: false,
  buttons: [
    {
      type: "primary",
      text: "确定",
      click: (e) => {
        
        submitBlog();
      },
    },
  ],
});

const submitBlog = () => {
  blogFormRef.value.validate(
          async (valid) => {
          if (!valid) {
            return;
          }
          blogFormRef.value.validate(async (valid)=>{
            if(!valid){
              return;
            }
            let params =Object.assign({}, blogFormData.value);
            let result = await proxy.Request({
              url: api.saveBlog,
              params: params,
            })
            if(!result){return;}
            proxy.Message.success("保存博客成功");
            closeWindow();
          })
        }
        );
}

const emit = defineEmits();
const closeWindow = () => {
  windowConfig.value.show = false;
  emit("callback");
  cleanTimer();
};

// 初始化
const init = (type, data) => {
  windowConfig.value.show = true;

  startTimer();

  nextTick(() => {
    if (blogFormRef.value) {
      blogFormRef.value.resetFields();
      blogFormData.value = {categoryId : data.categoryId,pBlogId:data.blogId};
    }
  });
  if (type === "add") {
    getUserInfo();
  } else if (type === "update") {
    getBlogDetail(data.blogId);
  }
};
defineExpose({ init });

const getUserInfo = async () => {
  let result = await proxy.Request({
    url: api.getUserInfo,
  });
  if (!result) {
    return;
  }
  blogFormData.value.editorType = result.data.editorType;
};

const getBlogDetail = async (blogId) => {
  let result = await proxy.Request({
    url: api.getBlogDetail,
    params: {
      blogId: blogId,
    },
  });
  if (!result) {
    return;
  }
  blogFormData.value = result.data;
  if (result.data.tag) {
    blogFormData.value.tag = result.data.tag.split("|");
  } else {
    blogFormData.value.tag = [];
  }
    console.log(blogFormData.value);

};

onUnmounted(() => {
  cleanTimer();
});
</script>



<style scoped lang="scss">
::v-deep(.is-error .title-input .el-input__wrapper) {
  box-shadow: none;
}

::v-deep(.textArea) {
  align-self: stretch;
  height: calc(90vh - 181px);
}

.title-input {
  width: 100%;
  border-bottom: 1px solid #dddddd;
  ::v-deep(.el-input__wrapper) {
    box-shadow: none;
  }
}
</style>